package com.xyq.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyq.common.core.constants.CacheConstants;
import com.xyq.common.core.enums.ResultCode;
import com.xyq.common.core.exception.ServiceException;
import com.xyq.common.redis.service.RedisService;
import com.xyq.friend.domain.question.HotQuestion;
import com.xyq.friend.domain.question.Question;
import com.xyq.friend.domain.question.es.QuestionES;
import com.xyq.friend.elasticsearch.QuestionRepository;
import com.xyq.friend.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QuestionCacheManager {
    @Autowired
    private RedisService redisService ;

    @Autowired
    private QuestionMapper questionMapper ;




    // 获取竞赛列表的总长度
    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }


    public void refresh() {
        // 取数据库里查, 同时 按 创建时间排序
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();

         // 存放到缓存里
        redisService.rightPushAll(CacheConstants.QUESTION_LIST , questionIdList) ;
    }

    public Long preQuestion(Long questionId) {
        long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        // 如果当前题目已经是第一题
        if(index ==0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION) ;
        }
        // 获取 上一题 的数据
     return redisService.indexForList(CacheConstants.QUESTION_LIST , index-1 , Long.class);
    }

    public Long nextQuestion(Long questionId) {
        long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        // 最后一题的下标
        Long lastIndex = getListSize() - 1;
        // 如果当前题目已经是最后一题
        if(index == lastIndex){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION) ;
        }
        // 获取 下一题 的数据
        return redisService.indexForList(CacheConstants.QUESTION_LIST , index+1 , Long.class);
    }
    private String getHotQuestionListKey(){
        return CacheConstants.HOT_QUESTION_LIST;
    }

}
